define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util = require('util');
	var view  = require('@base/view');

	// 重定向模块
	var PMP = view.container.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'class': 'M-character',
				'url': '',
				'auto_load': false
			});
			this.Super( 'init', arguments );
		},
		afterBuild:function() {
			var el = this.getDOM();

			el.addClass('pr');

			var c = this.getConfig();
			var type = c && c.param && c.param.Type || 1;
			this.$type = type;
			//PC
			var list;
			if(type == 1) {
				list = {
					'includeCookie': {
						'text': LANG("包含cookies人群"),
						'module': {
							'uri': 'modules/inEx.single',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'excludeCookie': {
						'text': LANG("排除cookies人群"),
						'module': {
							'uri': 'modules/inEx.single',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'includeIp': {
						'text': LANG("包含IP人群"),
						'module': {
							'uri': 'modules/inEx.single',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'excludeIp': {
						'text': LANG("排除IP人群"),
						'module': {
							'uri': 'modules/inEx.single',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					}
				};
			}
			//mobile
			else {
				list = {
					'includeDevice': {
						'text': LANG("包含设备人群"),
						'module': {
							'uri': 'modules/inEx.single',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'excludeDevice': {
						'text': LANG("排除设备人群"),
						'module': {
							'uri': 'modules/inEx.single',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					}
				};
			}

			this.createAsync('tab', '@base/common/base.tab', {
				'list': list
			});

			this.reset();
		},
		setParam: function(param) {
			this.$param = param;
			return this;
		},
		load: function(reload) {
			var c = this.getConfig();
			var param = util.extend({}, c.param, this.$param);

			if (c.auto_load) {
				pubjs.sync();
			}
			this.showLoading();
			pubjs.mc.send(c.url, param, this.onData.bind(this));
			return this;
		},
		onData: function(err, data) {
			var c = this.getConfig();
			if (c.auto_load) {
				pubjs.sync(true);
			}
			this.hideLoading();
			if (err) {
				return pubjs.alert(err.message);
			}
			this.setData(data);
		},
		setData: function(data) {
			if (data) {
				this.$data = data;

				var type = this.$type;
				//PC
				if(type == 1) {
					if (data.cookie) {
						this.get('tab/includeCookie').setData([data.cookie]);
						this.get('tab/excludeCookie').setData([data.cookie]);
					}
					if (data.ip) {
						this.get('tab/includeIp').setData([data.ip]);
						this.get('tab/excludeIp').setData([data.ip]);
					}
				}
				//MT
				else {
					if (data.device) {
						this.get('tab/includeDevice').setData([data.device]);
						this.get('tab/excludeDevice').setData([data.device]);
					}
				}
			}
			return this;
		},
		getData: function(data) {
			return this.$data;
		},
		// setValue后端转前端
		formatBackendSetValue: function(arr) {
			var formated = [];
			util.each(arr, function(item) {
				formated.push({
					id: item["VisitorCateId"],
					text: item["CateName"]
				});
			});
			var result = [];
			if(formated.length){
				result.push(formated);
			}
			return result;
		},
		setValue: function(value) {
			if (!value) {
				return;
			}
			if(this.$type == 1) {
				var ip = value.Ip || {};
				var cook = value.Cookie || {};

				this.get('tab/includeIp').setValue(this.formatBackendSetValue(ip.Include));
				this.get('tab/excludeIp').setValue(this.formatBackendSetValue(ip.Exclude));
				this.get('tab/includeCookie').setValue(this.formatBackendSetValue(cook.Include));
				this.get('tab/excludeCookie').setValue(this.formatBackendSetValue(cook.Exclude));
			}
			else {
				var device = value.Device || {};
				this.get('tab/includeDevice').setValue(this.formatBackendSetValue(device.Include));
				this.get('tab/excludeDevice').setValue(this.formatBackendSetValue(device.Exclude));
			}

			return this;
		},
		getValue: function() {
			var type = this.$type;
			var ret;
			var tmpExclude, tmpInclude;
			if(type == 1) {
				tmpExclude = this.get('tab/excludeCookie').getValue();
				tmpInclude = this.get('tab/includeCookie').getValue();
				var tmpIpEx = this.get('tab/excludeIp').getValue();
				var tmpIpIn = this.get('tab/includeIp').getValue();
				ret = {
					'Cookie': {
						'Include': tmpInclude[0] || []
						,'Exclude': tmpExclude[0] || []
					},
					'Ip': {
						'Include': tmpIpIn[0] || []
						,'Exclude': tmpIpEx[0] || []
					}
				}
			}
			else {
				tmpExclude = this.get('tab/excludeDevice').getValue();
				tmpInclude = this.get('tab/includeDevice').getValue();
				ret = {
					'Device': {
						'Include': tmpInclude[0] || []
						,'Exclude': tmpExclude[0] || []
					}
				}
			}

			return ret;
		},
		reset: function() {
			this.hideLoading();
			this.$param = {};
			this.$.tab.reset();
			return this;
		}
	});
	exports.base = PMP;

	// 新重定向模块
	var NewPDMP = view.container.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'class': 'M-characterNew',
				'url': '',
				'param': {
					'runstatus': 1
				},
				'auto_load': true
			});

			this.$dataReady = false;
			this.$valueCache = null;

			this.Super( 'init', arguments );
		},
		afterBuild:function() {
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			el.addClass('clear');

			el.append([
				'<div class="M-characterNewTab">',
					'<div pub-mod="@base/common/base.tab" pub-name="tab"/>',
				'</div>',
				'<div class="M-characterNewArrow">',
					'<i class="triangle-left"/>',
				'</div>',
				'<div class="M-characterNewResult">',
					'<div pub-mod="@base/common/base.tab" pub-name="tabResult"/>',
				'</div>'
			].join(''));

			self.$doms = {
				'selectTab': el.find('.M-characterNewTab'),
				'arrow': el.find('.M-characterNewArrow'),
				'resultTab': el.find('.M-characterNewResult')
			}


			var type = c && c.param && c.param.Type || 1;
			self.$type = type;
			//PC
			var list, list_result = {};
			if(type == 1) {
				list = {
					'includeCookie': {
						'text': LANG("包含cookies人群"),
						'module': {
							'uri': 'modules/treeSelect.tree',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'excludeCookie': {
						'text': LANG("排除cookies人群"),
						'module': {
							'uri': 'modules/treeSelect.tree',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'includeIp': {
						'text': LANG("包含IP人群"),
						'module': {
							'uri': 'modules/treeSelect.tree',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'excludeIp': {
						'text': LANG("排除IP人群"),
						'module': {
							'uri': 'modules/treeSelect.tree',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					}
				};
			}
			//mobile
			else {
				list = {
					'includeDevice': {
						'text': LANG("包含设备人群"),
						'module': {
							'uri': 'modules/treeSelect.tree',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					},
					'excludeDevice': {
						'text': LANG("排除设备人群"),
						'module': {
							'uri': 'modules/treeSelect.tree',
							'config': {
								'single': true,
								'class': 'M-characterContent'
							}
						}
					}
				};
			}

			util.each(list, function(item, idx){
				if(item){
					list_result[idx] = util.clone(item);
					list_result[idx].module.uri = 'modules/treeSelect.result';
					list_result[idx].module.config.hasLogic = true;
				}
			});

			self.buildFromTemplate({
				'tab': {
					'list': list,
					'silent': false,
					'tab_css': {
						'padding-left': 0,
						'padding-right': 0
					}
				},
				'result': {

				},
				'tabResult': {
					'list': list_result,
					'silent': false,
					'tab_css': {
						'padding-left': 0,
						'padding-right': 0
					}
				}
			});

			// self.load();
		},
		afterBuildTemplate: function(){

		},
		setParam: function(param) {
			this.$param = param;
			return this;
		},
		load: function(reload) {
			if(!this.$dataReady){
				this.showLoading();
				var c = this.getConfig();
				var param = util.extend({}, c.param, this.$param);

				if (c.auto_load) {
					pubjs.sync();
				}

				pubjs.mc.send(c.url, param, this.onData.bind(this));
			}
			return this;
		},
		onData: function(err, data) {
			var c = this.getConfig();
			if (c.auto_load) {
				pubjs.sync(true);
			}

			if (err) {
				return pubjs.alert(err.message);
			}
			this.setData(data);
			this.hideLoading();
			this.fire('dataLoadEnd');
		},
		setData: function(data) {
			this.$dataReady = true;
			if (data) {
				this.$data = data;

				var type = this.$type;
				//PC
				if(type == 1) {
					if (data.cookie) {
						this.get('tab/includeCookie').setData([data.cookie]);
						this.get('tab/excludeCookie').setData([data.cookie]);
					}
					if (data.ip) {
						this.get('tab/includeIp').setData([data.ip]);
						this.get('tab/excludeIp').setData([data.ip]);
					}
				}
				//MT
				else {
					if (data.device) {
						this.get('tab/includeDevice').setData([data.device]);
						this.get('tab/excludeDevice').setData([data.device]);
					}
				}
			}

			if(this.$valueCache){
				this.setValue(this.$valueCache);
				this.$valueCache = null;
			}

			return this;
		},
		getData: function(data) {
			return this.$data;
		},
		// setValue后端转前端
		formatBackendSetValue: function(arr) {
			var formated = [];
			util.each(arr, function(item) {
				formated.push({
					id: item["VisitorCateId"] || item["id"],
					text: item["CateName"] || item["text"],
					logic: item["PrevLogical"]
				});
			});
			var result = [];
			if(formated.length){
				result.push(formated);
			}
			return formated;
		},
		setValue: function(value) {
			if(this.$dataReady){
				if (!value) {
					return;
				}
				if(this.$type == 1) {
					var ip = value.Ip || {};
					var cook = value.Cookie || {};

					this.get('tab/includeIp').setValue(this.formatBackendSetValue(ip.Include), 'character');
					this.get('tab/excludeIp').setValue(this.formatBackendSetValue(ip.Exclude), 'character');
					this.get('tab/includeCookie').setValue(this.formatBackendSetValue(cook.Include), 'character');
					this.get('tab/excludeCookie').setValue(this.formatBackendSetValue(cook.Exclude), 'character');
				}
				else {
					var device = value.Device || {};
					this.get('tab/includeDevice').setValue(this.formatBackendSetValue(device.Include));
					this.get('tab/excludeDevice').setValue(this.formatBackendSetValue(device.Exclude));
				}
			}else{
				this.$valueCache = value;
			}

			return this;
		},
		getValue: function() {
			var self = this;
			var type = self.$type;
			var ret;
			var tmpExclude, tmpInclude, tmpIpEx, tmpIpIn;
			if(type == 1) {
				tmpExclude = _getFiledsInArray(self.get('tabResult/excludeCookie').getData());
				tmpInclude = _getFiledsInArray(self.get('tabResult/includeCookie').getData());
				tmpIpEx = _getFiledsInArray(self.get('tabResult/excludeIp').getData());
				tmpIpIn = _getFiledsInArray(self.get('tabResult/includeIp').getData());
				ret = {
					'Cookie': {
						'Include': tmpInclude || []
						,'Exclude': tmpExclude || []
					},
					'Ip': {
						'Include': tmpIpIn || []
						,'Exclude': tmpIpEx || []
					}
				}
			}
			else {
				tmpExclude = _getFiledsInArray(self.get('tabResult/excludeDevice').getData());
				tmpInclude = _getFiledsInArray(self.get('tabResult/includeDevice').getData());
				ret = {
					'Device': {
						'Include': tmpInclude || []
						,'Exclude': tmpExclude || []
					}
				}
			}

			return ret;
		},
		reset: function() {
			this.$valueCache = null;
			// this.hideLoading();
			this.$param = {};
			this.$.tab.reset();
			this.$.tabResult.reset();
			return this;
		},
		getFiledsInArray: function(data){
			var result = [];
			util.each(data, function(item){
				result.push(_getFiledsInArray(item));
			});
			return result;
		},
		onTabChange: function(ev){
			var subName = ev.param.name;
			this.get('tabResult').switchTab(subName);
			this.get('tab').switchTab(subName);
			return false;
		},
		// 左侧树形选择模块的选项点击消息
		onTreeItemClicked: function( ev ) {
			var self = this;
			var name = ev.name;
			var param = ev.param;
			var result = self.get('tabResult/'+name);
			var format = _formatTreeData( param );
			// 结果框添加一条
			result.addOne( format );
			return false;
		},
		// 右侧结果选项删除同步到左侧的选中状态
		onResultItemRemove: function( ev ) {
			var self = this;
			var name = ev.name;
			var id = ev.param;
			var tree = self.get('tab/'+name);
			tree.unChecked( id );
			return false;
		},
		// 树形模块setValue之后再设值result模块
		onTreeItemSetValued: function( ev ) {
			var self = this;
			var name = ev.name;
			var param = ev.param;
			var result = self.get('tabResult/'+name);
			result.setValue(param, 'character');
			return false;
		},
		// 树形清空已选
		onEmptyTreeItemSelected: function(ev){
			var self = this;
			var param = ev.param;
			var name = ev.name;
			var result = self.get('tabResult/'+name);
			if(param.length){
				util.each(param, function(item){
					result.addOne(item);
				});
			}
			return false;
		}
	});
	exports.newPDMP = NewPDMP;


	// 取出数组中元素的id和text字段,返回新数组
	function _getFiledsInArray( arr ) {
		var retArr = [], i = 0, len = arr.length;
		for( ; i < len; i++ ) {
			retArr.push({
				'id': arr[i]['id'],
				'text': arr[i]['text'],
				'PrevLogical': arr[i]['logic'] || 'or'
			});
		}
		return retArr;
	}

	// 将选中的数据格式化
	function _formatTreeData( dataArr ) {
		var i = 0, len = dataArr.length, ret, textArr = [], ids = [];
		for( ; i < len; i++ ) {
			textArr.unshift( dataArr[i].text );
			ids.unshift( dataArr[i].id );
		}
		ret = {
			'ids': ids,
			'texts': textArr.join(' / '),
			'id': dataArr[0]['id'],
			'text': dataArr[0]['text'],
			'logic': dataArr[0]['logic']
		}
		return ret;
	}
});